package com.example.myapplicationktkt2.notification


import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationCompat
import com.example.myapplicationktkt2.MainActivity
import com.example.myapplicationktkt2.R

object NotificationHelper {
    private const val CHANNEL_ID = "important_channel"

    fun sendNotification(context: Context, msg: String) {
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // 通知渠道配置（只创建一次，Android 8.0+ 必须）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "重要消息通知",
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                enableVibration(true)
                vibrationPattern = longArrayOf(0, 300, 200, 300)

                val soundUri =
                    Uri.parse("android.resource://${context.packageName}/${R.raw.notification_sound}")
                val audioAttr = AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build()
                setSound(soundUri, audioAttr)
            }
            manager.createNotificationChannel(channel)
        }

        // 点击通知跳回 MainActivity
        val intent = Intent(context, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_IMMUTABLE
        )

        //  内容加上时间，避免被认为是重复通知
        val finalMsg = "$msg (${System.currentTimeMillis()})"


        // 设置大图标
        val largeIcon = BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)

        val notification = NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle("📢 新提醒")
            .setContentText(finalMsg)
            .setStyle(NotificationCompat.BigTextStyle().bigText(finalMsg))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setLargeIcon(largeIcon)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL) // 声音+震动+灯光
            .build()

        // ⚠️ 每次生成一个新的 ID，确保不会被覆盖
        val notificationId = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
        manager.notify(notificationId, notification)
    }
}